package bounjour.ui;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import bounjour.Post;

import java.io.*;

public class Home extends BaseServlet {
	private static final long serialVersionUID = 1L;

	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		map.put("title", "Bounjour");
		map.put("message", "Create your post!");
		if (request.getParameter("userID") != null) {
			map.put("posts", Post.getPosts(Integer.parseInt(request.getParameter("userID"))));
		} else if (request.getParameter("tag") != null) {
			map.put("posts", Post.getPosts(request.getParameter("tag")));
		} else {
			map.put("posts", Post.getPosts());
		}
		process(request, response, "home.ftl");
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		
		if (getUser(request) != null) {
			Post post = new Post();
			post.setBody(request.getParameter("message"));
			post.setUserID(getUser(request).getId());
			post.save();
			
			response.sendRedirect("ViewPost?id=" + post.getID() + "&mode=edit");
		} else {
			response.sendRedirect("Login");
		}
	}

}
